//
//  RMMMyHuLiViewController.m
//  Romomo
//
//  Created by puman on 2017/1/4.
//  Copyright © 2017年 mazegong. All rights reserved.
//

#import "RMMMyHuLiViewController.h"
#import "RMMMyHuLiEmpatyView.h"
#import "RMMMyHuLiHeadView.h"
#import "RMMMyHuLiTableViewCell.h"
#import "RMMHuLiDetailsViewController.h"
#import "RMMGoodsConfirmViewController.h"
#import "RMMShopingModel.h"

@interface RMMMyHuLiViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation RMMMyHuLiViewController
{
    RMMMyHuLiEmpatyView *_empatyView;
    RMMNotNetWorkView *_networkView;
    NSMutableDictionary *_dataDic;
    UITableView *_tableView;
    UIButton *_bottomBut;
    NSInteger _buttonTag;
    NSString *_isHome;
}
- (void)dealloc{
    NS_REM(@"MUHUILIUPDATE", nil);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的护理疗程";
    self.view.backgroundColor = kWhiteColor;
    [self addSubViews];
    NS_ADD(update, @"MUHUILIUPDATE", nil);
    [self getMyTaoCanData];
}
- (void)update{
    [self getMyTaoCanData];
}
// 获取我的套餐
- (void)getMyTaoCanData{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"cust_id"] = [RMMFileManager shareHandle].userDic[@"CUST_ID"];
    NSString *url = GetCustBomUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic network:^(BOOL isNetwork) {
        if (!isNetwork) {
            _networkView.hidden = NO;
        } else {
            _networkView.hidden = YES;
        }
    } method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        _networkView.hidden = YES;
        if ([status isEqualToString:@"1"]) {
            [_dataDic removeAllObjects];
            NSArray *array = dataDic[@"data"];
            for (NSDictionary *dic in array) {
                NSArray *arr = dic[@"CARD_DETAILS"];
                for (NSDictionary *newDic in arr) {
                    RMMHuLiModel *model = [[RMMHuLiModel alloc] init];
                    [model setValuesForKeysWithDictionary:[RMMFileManager setValueForDic:newDic]];
                    model.isSelect = @"0";
                    model.COUNT = @"1";
                    model.BOM_ID = dic[@"BOM_ID"];
                    model.IS_DELAY = [NSString stringWithFormat:@"%@",dic[@"IS_DELAY"]];
                    if ([model.IS_HOME isEqualToString:@"1"]) {
                        NSMutableArray *value = _dataDic[@"上门服务套餐"];
                        if (value == nil) {
                            value = [NSMutableArray array];
                            [_dataDic setObject:value forKey:@"上门服务套餐"];
                        }
                        [value addObject:model];
                    } else {
                        NSMutableArray *value = _dataDic[@"到店服务套餐"];
                        if (value == nil) {
                            value = [NSMutableArray array];
                            [_dataDic setObject:value forKey:@"到店服务套餐"];
                        }
                        [value addObject:model];
                    }
                }
            }
            for (int i = 0; i < _dataDic.count; i++) {
                NSString *key = [_dataDic allKeys][i];
                NSMutableArray *value = _dataDic[key];
                if (value.count) {
                    [self sortArrayWith:value];
                }
            }
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_tableView reloadData];
        if ([_dataDic allKeys].count) {
            _empatyView.hidden = YES;
        } else {
            _empatyView.hidden = NO;
        }
    } error:^(NSError *errors) {
        _networkView.hidden = NO;
    } view:self.view];
}
- (void)sortArrayWith:(NSMutableArray *)array{
    NSMutableArray *arrayA = [NSMutableArray array];
    NSMutableArray *arrayB = [NSMutableArray array];
    
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSString *string = [inputFormatter stringFromDate:date];
    
    for (RMMHuLiModel *model in array) {
        NSString *time = [RMMFileManager retrunObjWith:model.END_DATE];
        if ([model.AVA_QTY integerValue] == 0) {
            [arrayA addObject:model];
        } else {
            if ([time compare:string] == NSOrderedAscending) {
                [arrayA addObject:model];
            } else {
                [arrayB addObject:model];
            }
        }
    }
    if (arrayB.count >= 1) {
        for (int i = 0; i < arrayB.count - 1; i++) {
            int maxIndex = i;
            for (int j = i+ 1; j < arrayB.count; j++) {
                RMMHuLiModel *modelA = arrayB[j];
                RMMHuLiModel *modelB = arrayB[maxIndex];
                if ([modelA.MY_CARD_ID floatValue] > [modelB.MY_CARD_ID floatValue]) {
                    maxIndex = j;
                }
            }
            if (i != maxIndex) {
                [arrayB exchangeObjectAtIndex:i withObjectAtIndex:maxIndex];
            }
        }
    }
    [array removeAllObjects];
    [array addObjectsFromArray:arrayB];
    [array addObjectsFromArray:arrayA];
}

- (void)addSubViews{
    _buttonTag = 1;
    _isHome = @"1";
    _dataDic = [NSMutableDictionary dictionary];
    
    RMMMyHuLiHeadView *headView = [[RMMMyHuLiHeadView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 54)];
    [self.view addSubview:headView];
    for (int i = 0; i < 2; i++) {
        UIButton *button = [self.view viewWithTag:1 + i];
        BUTTON_S(button, buttonClick:);
    }
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, headView.bottom, kScreenWideth, kScreenHeight - 64 - headView.bottom - 49) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = NO;
    [_tableView registerClass:[RMMMyHuLiTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:_tableView];
    [self addBottomView];
    
    _networkView = [[RMMNotNetWorkView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight)];
    _networkView.hidden = YES;
    BUTTON_S(_networkView.button, update);
    [self.view addSubview:_networkView];
    
    _empatyView = [[RMMMyHuLiEmpatyView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _empatyView.hidden = YES;
    BUTTON_S(_empatyView.buyBut, goBuyBut);
    [self.view addSubview:_empatyView];
}
- (void)goBuyBut{
    NS_POST(@"GOTOBUYSERVICES", nil, nil);
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)buttonClick:(UIButton *)button{
    _buttonTag = button.tag;
    for (int i = 0; i < 2; i++) {
        UIButton *buttons = [self.view viewWithTag:1 + i];
        if (buttons.tag == _buttonTag) {
            [buttons setTitleColor:COLORFROMCODE(0x2C2C2C, 1) forState:(UIControlStateNormal)];
            buttons.backgroundColor = COLORFROMCODE(0xEEEEEE, 1);
            buttons.userInteractionEnabled = NO;
        } else {
            [buttons setTitleColor:COLORFROMCODE(0xBFBFBF, 1) forState:(UIControlStateNormal)];
            buttons.backgroundColor = kWhiteColor;
            buttons.userInteractionEnabled = YES;
        }
    }
    if (_buttonTag == 1) {
        _isHome = @"1";
    } else {
        _isHome = @"0";
    }
    [RMMFileManager butOffWithBut:_bottomBut];
    NSArray *array = [_dataDic allKeys];
    for (int i = 0; i < array.count; i++) {
        NSString *key = array[i];
        NSMutableArray *value = _dataDic[key];
        for (int j = 0; j < value.count; j++) {
            RMMHuLiModel *model = value[j];
            model.isSelect = @"0";
        }
    }
    [_tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *array = [_dataDic allKeys];
    if (!array.count) {
        return 0;
    }
    NSString *key = nil;
    if (_buttonTag == 1) {
        key = @"上门服务套餐";
    } else {
        key = @"到店服务套餐";
    }
    NSMutableArray *value = _dataDic[key];
    return value.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 160;
}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 40)];
//    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 40)];
//    label.font = kFont(16);
//    NSDictionary *dic = _dataArray[section];
//    label.text = [RMMFileManager retrunObjWith:dic[@"BOM_NAME"]];
//    [view addSubview:label];
//    return view;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return 40;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RMMMyHuLiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    NSString *key = nil;
    if (_buttonTag == 1) {
        key = @"上门服务套餐";
    } else {
        key = @"到店服务套餐";
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSMutableArray *value = _dataDic[key];
    RMMHuLiModel *model = value[indexPath.row];
    cell.model = value[indexPath.row];
    cell.selectBut.tag = indexPath.row + 10000;
    cell.subBut.tag = indexPath.row + 20000;
    cell.addBut.tag = indexPath.row + 30000;
    BUTTON_S(cell.selectBut, cellSelectButClick:);
    BUTTON_S(cell.subBut, subButClick:);
    BUTTON_S(cell.addBut, addButClick:);
    
    if ([model.COUNT isEqualToString:@"1"]) {
        [cell.subBut setImage:[UIImage imageNamed:@"un-subtract@3x"] forState:(UIControlStateNormal)];
        cell.subBut.userInteractionEnabled = NO;
    } else {
        [cell.subBut setImage:[UIImage imageNamed:@"subtract@3x"] forState:(UIControlStateNormal)];
        cell.subBut.userInteractionEnabled = YES;
    }
    return cell;
}
- (void)cellSelectButClick:(UIButton *)button{
    NSInteger row = button.tag - 10000;
    NSString *key = nil;
    if (_buttonTag == 1) {
        key = @"上门服务套餐";
    } else {
        key = @"到店服务套餐";
    }
    NSMutableArray *value = _dataDic[key];
    RMMHuLiModel *model = value[row];
    if ([model.isSelect isEqualToString:@"1"]) {
        model.isSelect = @"0";
        [button setImage:[UIImage imageNamed:@"可选@3x"] forState:(UIControlStateNormal)];
    } else {
        model.isSelect = @"1";
        [button setImage:[UIImage imageNamed:@"选中@3x"] forState:(UIControlStateNormal)];
    }
    for (RMMHuLiModel *model in value) {
        if ([model.isSelect isEqualToString:@"1"]) {
            [RMMFileManager butOnWithBut:_bottomBut];
            return;
        } else {
            [RMMFileManager butOffWithBut:_bottomBut];
        }
    }
    [_tableView reloadData];
}
- (void)subButClick:(UIButton *)button{
    NSString *key = nil;
    if (_buttonTag == 1) {
        key = @"上门服务套餐";
    } else {
        key = @"到店服务套餐";
    }
    NSMutableArray *value = _dataDic[key];
    NSInteger row = button.tag - 20000;
    RMMHuLiModel *model = value[row];
    NSInteger cout = [model.COUNT integerValue];
    if (cout == 1) {
        [button setImage:[UIImage imageNamed:@"un-subtract@3x"] forState:(UIControlStateNormal)];
        button.userInteractionEnabled = NO;
    } else {
        cout -= 1;
        model.COUNT = [NSString stringWithFormat:@"%ld",cout];
    }
    [_tableView reloadData];
}
- (void)addButClick:(UIButton *)button{
    NSString *key = nil;
    if (_buttonTag == 1) {
        key = @"上门服务套餐";
    } else {
        key = @"到店服务套餐";
    }
    NSMutableArray *value = _dataDic[key];
    NSInteger row = button.tag - 30000;
    RMMHuLiModel *model = value[row];
    NSInteger cout = [model.COUNT integerValue];
    NSInteger ava_qty = [model.AVA_QTY integerValue];
    if (cout == ava_qty) {
        [RMMFileManager MBProgressWith:@"可用次数不足!" onView:self.view];
        return;
    }
    cout += 1;
    model.COUNT = [NSString stringWithFormat:@"%ld",cout];
    [_tableView reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *key = nil;
    if (_buttonTag == 1) {
        key = @"上门服务套餐";
    } else {
        key = @"到店服务套餐";
    }
    NSMutableArray *value = _dataDic[key];
    RMMHuLiModel *model = value[indexPath.row];
    NSString *time = [RMMFileManager retrunObjWith:model.END_DATE];
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSString *string = [inputFormatter stringFromDate:date];
    if ([time compare:string] == NSOrderedAscending || [model.AVA_QTY integerValue] == 0){
        return;
    } else {
        RMMHuLiDetailsViewController *VC = [[RMMHuLiDetailsViewController alloc] init];
        VC.model = model;
        VC.isHome = _isHome;
        [self.navigationController pushViewController:VC animated:YES];
    }
}
- (void)addBottomView{
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 49 - 64, kScreenWideth, 49)];
    bottomView.backgroundColor = kWhiteColor;
    [self.view addSubview:bottomView];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, bottomView.width, 0.5)];
    lineLabel.backgroundColor = RGBA(221, 221, 221, 1);
    [bottomView addSubview:lineLabel];
    
    _bottomBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _bottomBut.frame = CGRectMake(kScreenWideth / 2 - 90, 6.5, 4 * kHalf - kMaric, 36);
    _bottomBut.titleLabel.font = kBFont(14);
    _bottomBut.layer.masksToBounds = YES;
    _bottomBut.layer.cornerRadius = 18;
    [_bottomBut setTitle:@"预约服务" forState:(UIControlStateNormal)];
    [RMMFileManager butOffWithBut:_bottomBut];
    BUTTON_S(_bottomBut, nextButClick);
    [bottomView addSubview:_bottomBut];
}
- (void)nextButClick{
    RMMGoodsConfirmViewController *VC = [[RMMGoodsConfirmViewController alloc] init];
    VC.goodsArray = [NSMutableArray array];
    NSString *key = nil;
    if (_buttonTag == 1) {
        key = @"上门服务套餐";
    } else {
        key = @"到店服务套餐";
    }
    NSMutableArray *value = _dataDic[key];
    NSMutableArray *mArray = [NSMutableArray array];
    for (RMMHuLiModel *model in value) {
        if ([model.isSelect isEqualToString:@"1"]) {
            [mArray addObject:model];
            RMMShopingModel *taoModel = [[RMMShopingModel alloc] init];
            taoModel.IMAGEURL = model.SER_URL;
            taoModel.SERVICE_ID = [NSString stringWithFormat:@"%@",model.SERVER_ID];
            taoModel.PRICE = [NSString stringWithFormat:@"%@",model.PRICE];
            taoModel.COUNT = [NSNumber numberWithInteger:[model.COUNT integerValue]];
            taoModel.SERVICE_NAME = model.NAME;
            taoModel.MY_CARD_ID = [NSString stringWithFormat:@"%@",model.MY_CARD_ID];
            taoModel.TIME_LEN = model.TIME_LEN;
            taoModel.PROD_SERVICE_TYPE = model.PROD_SERVICE_TYPE;
            [VC.goodsArray addObject:taoModel];
        }
    }
    if (VC.goodsArray.count == 1) {
        RMMShopingModel *model = VC.goodsArray[0];
        if ([model.PROD_SERVICE_TYPE isEqualToString:@"1"] && ([model.COUNT isEqualToNumber:@1])) {
            [RMMFileManager MBProgressWith:@"辅助项目不能单独购买!" onView:self.view];
            return;
        }
    }
    VC.isHome = _isHome;
    [self.navigationController pushViewController:VC animated:YES];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
